<?php
namespace Modules\Payment\Entities;

use Modules\Payment\Entities\PaymentRecord;

use ThrowException;
use ByteDance;
use Cache;

use Modules\Core\Helpers\HttpClient;
use Surpaimb\KuaiShou\Factory;

class KuaishouPay
{
	protected $clientName;
	protected $payType;
	protected $pay;
	protected $app;

	public function __construct($clientName, $payType)
	{
		$this->payType = $payType;
		$this->clientName = $clientName;

		$config = config('kuaishou.mini_program.default');
        $this->app = Factory::make('miniProgram', $config);
        $this->pay = $this->app->kuaishou_payment;
	}

	public function __call($name, $arguments)
    {
    	return call_user_func_array(array($this->pay, $name), $arguments);
    }

	public function config($user, $order)
	{
		$money = $order->payPrice();


		$title = $order->title();
		
		$number = $order->number . '_' . date('is');

		$order->update([
			'pay_number' => $number
		]);

		$uuid = $order->uuid;
		$body = '普通商品';

		$openId = @$user->kuaishou_accounts()->first()->openid;

		// $openId = 'f198f44982a0c36314bf572448c99ae8';

		if (!$openId) {
			ThrowException::Conflict('用户Openid不存在~');
		}

		$info = [
			'out_order_no' => $number,
			'total_amount' => $money,
			'open_id' =>  $openId,
			'subject' => $title,
			'detail' => $body,
			'type' => 1,
			// 'valid_time' => 300,
			'expire_time' => 1800,
			// 'cp_extra' => $uuid,
			'notify_url' => env('APP_URL') . '/payment-callback/kuaishou',
			'attach' => $uuid
			// 'disable_msg' => 0,
		];

		// \Log::error($info);

		$res = $this->pay->unify($info);

		if (@$res['result'] !== 1 || !@$res['order_info']) {
			\Log::error('下单失败' . $order->id);
			\Log::error($res);
			ThrowException::Conflict('下单失败~');
		}

		return $res['order_info'];

		// return $this->pay->pay($uuid, $number, $money,  $title, [
		// 	'body' => '测试商品',
		// 	'notify_url' => 'https://baidu.com/'
		// ]);
	}

	// 检验回调结果
	public function checkCallbackData($req)
	{
		$body = $req->post();
		$body = json_encode($body) . env('KUAISHOU_APP_SECRET');
		$sign = md5($body);
		
		return $req->header('kwaisign') === $sign;
	}

	// 签名
	public function sign($data, $type = 'md5')
	{
		foreach ($data as $key => $value) {
			$data[$key] = trim($data[$key]);
		}
		sort($data, 2);

		if ($type === 'md5') {
			return md5(implode("&", $data));
		}
		elseif ($type === 'sha1') {
			return sha1(implode("", $data));
		}
	}

	public function refundMoney($order, $refundMoney = null, $options = []) 
	{
		// $payment = $order->payment() ?: ThrowException::Conflict('订单无支付记录');

		// \Log::error($payment);
		// exit();

		// $orderType = 'single_order';

		// $remark = @v($options['remark'], '订单退款');

		// // $paymentRecord = $order->payment();
		// $number = $order->pay_number;

		// // \Log::error($number);
		// // exit();

		// $info = [
		// 	'out_trade_no' => $number,
		// 	'out_refund_no' => time(),
		// 	'total_fee' => $order->pay_money_price,
		// 	'refund_fee' => $refundMoney,
		// 	'refund_desc' => $remark,
		// ];

		// try {
		// 	$res = $this->pay->refund($info);
		// }
		// catch(\Yansongda\Pay\Exceptions\GatewayException $e) {
		// 	\Log::error('订单: ' . $order->id . ' 退款失败:' . $e->getMessage());
		// 	ThrowException::Conflict('退款失败, 请检查退款金额是否超出总订单金额');
		// }
	}


	public function recordPayment($order, $clientName, $paySubType, $data, $options = [])
	{
		$info = [
			'trade_number' => @$data['transaction_id'],
			'out_trade_number' => @$data['out_trade_no'],
			'client_name' => $clientName,
			'pay_type' => 'wechat',
			'pay_sub_type' => @$paySubType,
			'paid_at' => @$data['time_end'],
			'money' => @$data['total_fee'] ?: $order->pay_money_price,
			'status' => 2,
			'options' => $data
		];

		if ($order->number[0] == 'U') 
			$info['union_order_id'] = $order->id;
		else
			$info['order_id'] = $order->id;

		$record = PaymentRecord::create($info);

		$record->save();
	}

	public function success()
	{
		return [
          "err_no" => 0,
          "err_tips" => "success"
        ];
	}
}
